package com.piggymetrics.account.service;

import com.piggymetrics.account.client.AuthServiceClient;
import com.piggymetrics.account.client.StatisticsServiceClient;
import com.piggymetrics.account.domain.Account;
import com.piggymetrics.account.domain.Currency;
import com.piggymetrics.account.domain.Saving;
import com.piggymetrics.account.domain.User;
import com.piggymetrics.account.repository.AccountRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.util.Date;

//accout接口的实现
@Service
public class AccountServiceImpl implements AccountService {

    //来一个日志记录
	private final Logger log = LoggerFactory.getLogger(getClass());

	//这里是需要调用的几个微服务，原来是在这里调用。
	@Autowired
	private StatisticsServiceClient statisticsClient;

	@Autowired
	private AuthServiceClient authClient;

	//这个来调用，account的dao层
	@Autowired
	private AccountRepository repository;

	/**
	 * 通过用户名查找账务
	 */
	@Override
	public Account findByName(String accountName) {
	    //利用断言，来判断是否有数据
		Assert.hasLength(accountName);
		return repository.findByName(accountName);
	}

	/**
	 * 创建一个账务，通过用户来创建
	 */
	@Override
	public Account create(User user) {

        //查询一下这个用户的账务存在吗。
		Account existing = repository.findByName(user.getUsername());
		//如果是空的就继续下一个，
        // 不是空的就抛出异常，信息是后一个参数
		Assert.isNull(existing, "账户已经存在" + user.getUsername());

		//todo 这里不知道为什么还要新建用户？？？
		authClient.createUser(user);

		//todo 这里估计是账户的内容
		Saving saving = new Saving();
		saving.setAmount(new BigDecimal(0));
		saving.setCurrency(Currency.getDefault());
		saving.setInterest(new BigDecimal(0));
		saving.setDeposit(false);
		saving.setCapitalization(false);

		Account account = new Account();
		account.setName(user.getUsername());
		account.setLastSeen(new Date());
		account.setSaving(saving);

		repository.save(account);

		log.info("new account has been created: " + account.getName());

		return account;
	}

	/**
	 * 保存更改
	 */
	@Override
	public void saveChanges(String name, Account update) {

		Account account = repository.findByName(name);
		Assert.notNull(account, "can't find account with name " + name);

		account.setIncomes(update.getIncomes());
		account.setExpenses(update.getExpenses());
		account.setSaving(update.getSaving());
		account.setNote(update.getNote());
		account.setLastSeen(new Date());
		repository.save(account);

		log.debug("account {} changes has been saved", name);

		statisticsClient.updateStatistics(name, account);
	}
}
